package com.ymatou.iapi.quickturnover.testcase;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.quickturnover.parameter.CreateAdvanceOrderReqBean;
import com.ymatou.iapi.quickturnover.service.AdvanceOrderService;
import com.ymatou.iapi.quickturnover.service.CreateAdvanceOrderReqCall;
import com.ymatou.iapi.trading.operate.parameter.req.ApplySalesRefundRequestBean;
import com.ymatou.operate.trading.api.parameter.DispatchedBean;
import com.ymatou.operate.trading.api.service.DispatchedCall;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.common.enums.BillTypeEnum;
import com.ymttest.database.model.AdvanceOrder;
import com.ymttest.database.sqlwapper.AdvanceOrderDefaultWapper;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
/**
*创建预支单(贝海发货成功后)接口
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_CreateAdvanceOrderReq {
	private static CreateAdvanceOrderReqBean createadvanceorderreqBean;
	private static CreateAdvanceOrderReqCall createadvanceorderreqCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("创建预支单(贝海发货成功后)接口");
	}

	@Before
	public void caseUp() {
		createadvanceorderreqBean = new CreateAdvanceOrderReqBean();
		createadvanceorderreqCall = new CreateAdvanceOrderReqCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(createadvanceorderreqCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_001() {
		Logger.start(true, "创建预支单(贝海发货成功后)成功");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);

			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");

			String BillCode = EnvSetup.getEnv().equals("sit1")
					? AdvanceOrderService.billCode_sit1
					: AdvanceOrderService.billCode_uat;

			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(BillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":false,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();
			//商家发货 
			orderService.dispatchedByXlobo(orderId, sellerId);

			Thread.sleep(3000);

			Logger.comment("准备前置数据结束");

			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			//createadvanceorderreqCall.callService();			
			//Logger.verifyEquals("ok", createadvanceorderreqCall.getReturnData(), "验证接口返回ok");		
			// 订单资金表
			List<Map> ymtOrderState = new DefaultWapper()
					.selectOrderStateByOderId(orderId);
			// 订单定金支付的金额
			BigDecimal fPaidAmountOfCash = (BigDecimal) ymtOrderState.get(0)
					.get("fPaidAmountOfCash");
			// 订单补款金额
			BigDecimal fPostPaidAmountOfCash = (BigDecimal) ymtOrderState
					.get(0).get("fPostPaidAmountOfCash");
			//ymt 优惠券
			BigDecimal YmtCouponAmount = (BigDecimal) ymtOrderState.get(0).get(
					"fPaidAmountOfYmtCoupon");

			BigDecimal order_amount = fPaidAmountOfCash.add(
					fPostPaidAmountOfCash).add(YmtCouponAmount);

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(1, advanceOrderList.size(),
					"验证advance_order 记录");

			Logger.comment("校验advance_order表");
			advanceOrderList.forEach(advanceOrder -> {
				Logger.verifyEquals(order_amount,
						advanceOrder.getOrder_amount(), "验证order_amount");
				Logger.verifyEquals(1, advanceOrder.getAdvance_status(),
						"验证advance_status");
				Logger.verifyEquals(sellerId, advanceOrder.getSeller_id(),
						"验证seller_id");
				Logger.verifyEquals(orderId, advanceOrder.getOrder_id(),
						"验证orderId");
			});
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_002() {
		Logger.start(true, "订单不是发货状态，创建失败");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			//商家发货 
			//orderService.dispatchedByXlobo(orderId, sellerId); 
			Logger.comment("准备前置数据结束");

			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(0, advanceOrderList.size(),
					"验证advance_order 记录");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_003() {
		Logger.start(true, "订单不是用贝海物流发货,创建失败");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);

			//商家发货 
			DispatchedBean dispatchedbean = new DispatchedBean();
			DispatchedCall dispatchedcall = new DispatchedCall();
			dispatchedbean.setBillType(BillTypeEnum.YMTAPI);
			// 物流单号
			dispatchedbean.setDeliverSummary(TestDataManager.randomStr(10));
			// Logger.debug(DeliverSummary);
			dispatchedbean.setDeliverType("0");
			dispatchedbean.setOrderId(orderId);
			dispatchedbean.setProvider("贝海");
			dispatchedbean.setSellerUserId(sellerId);

			BigDecimal Weight = new BigDecimal(10);
			dispatchedbean.setWeight(Weight);// 重量
			dispatchedbean.setIsShippedByXlobo(false);
			dispatchedcall.setData(false, dispatchedbean);
			Logger.comment("订单:" + orderId + "卖家:" + sellerId + "发货");
			dispatchedcall.callService();
			Logger.comment("准备前置数据结束");

			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(0, advanceOrderList.size(),
					"验证advance_order 记录");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_004() {
		Logger.start(true, "订单接单后,发生退款退货，创建失败");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			// 申请退款
			ApplySalesRefundRequestBean applySalesRefundRequestBean = orderService
					.applySalesRefundRequestInJavaBean(orderId);
			applySalesRefundRequestBean.getSalesRefundInfoList().get(0)
					.setRefundAmount(BigDecimal.TEN);
			orderService
					.applySalesRefundRequestCall(applySalesRefundRequestBean);
			// 退款执行
			orderService.salesrefundsuccessrequest(applySalesRefundRequestBean);
			//商家发货 
			//orderService.dispatchedByXlobo(orderId, sellerId); 

			Logger.comment("准备前置数据结束");

			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(0, advanceOrderList.size(),
					"验证advance_order 记录");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_005() {
		Logger.start(true, "订单已创建预支单,重复创建失败");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);
			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			String BillCode = EnvSetup.getEnv().equals("sit1")
					? AdvanceOrderService.billCode_sit1
					: AdvanceOrderService.billCode_uat;
			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(BillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":false,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();
			//商家发货 
			orderService.dispatchedByXlobo(orderId, sellerId);

			Thread.sleep(3000);

			Logger.comment("准备前置数据结束");
			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");
			// 订单资金表
			List<Map> ymtOrderState = new DefaultWapper()
					.selectOrderStateByOderId(orderId);
			// 订单定金支付的金额
			BigDecimal fPaidAmountOfCash = (BigDecimal) ymtOrderState.get(0)
					.get("fPaidAmountOfCash");
			// 订单补款金额
			BigDecimal fPostPaidAmountOfCash = (BigDecimal) ymtOrderState
					.get(0).get("fPostPaidAmountOfCash");
			//ymt 优惠券
			BigDecimal YmtCouponAmount = (BigDecimal) ymtOrderState.get(0).get(
					"fPaidAmountOfYmtCoupon");

			BigDecimal order_amount = fPaidAmountOfCash.add(
					fPostPaidAmountOfCash).add(YmtCouponAmount);

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(1, advanceOrderList.size(),
					"验证advance_order 记录");

			Logger.comment("校验advance_order表");
			advanceOrderList.forEach(advanceOrder -> {
				Logger.verifyEquals(order_amount,
						advanceOrder.getOrder_amount(), "验证order_amount");
				Logger.verifyEquals(1, advanceOrder.getAdvance_status(),
						"验证advance_status");
				Logger.verifyEquals(sellerId, advanceOrder.getSeller_id(),
						"验证seller_id");
				Logger.verifyEquals(orderId, advanceOrder.getOrder_id(),
						"验证orderId");
			});
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_006() {
		Logger.start(false, "买手未开通快周转服务，创建预支单失败");
		try {
			OrderCallService orderService = new OrderCallService();
			Logger.comment("准备前置数据");
			Map map = orderService.appSaveOrder();

			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");
			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);
			//申请补款
			/*            BigDecimal payAmount=BigDecimal.TEN;
			            orderService.applyForPostPay(orderId, sellerId, payAmount);
			            //买家补款
			            orderService.orderPostPayRequest(userId, payAmount, orderId);*/

			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");

			String BillCode = EnvSetup.getEnv().equals("sit1")
					? AdvanceOrderService.billCode_sit1
					: AdvanceOrderService.billCode_uat;

			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(BillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":false,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();
			//商家发货 
			orderService.dispatchedByXlobo(orderId, sellerId);

			Logger.comment("准备前置数据结束");

			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(0, advanceOrderList.size(),
					"验证advance_order 记录");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_007() {
		Logger.start(false, "订单号不存在");
		try {
			int orderId = 1111;
			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("ok",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

			AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			Logger.verifyEquals(0, advanceOrderList.size(),
					"验证advance_order 记录");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_CreateAdvanceOrderReq_008() {
		Logger.start(false, "订单号为null");
		try {
			int orderId = 111111;
			//createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(createadvanceorderreqBean);
			createadvanceorderreqCall.callService();
			Logger.verifyEquals("fail",
					createadvanceorderreqCall.getReturnData(), "验证接口返回ok");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}